package com.ruoyi.functiontest.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.functiontest.domain.RoadInterchangeTest;
import com.ruoyi.functiontest.service.IRoadInterchangeTestService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 枢纽互通里程实测数据测试Controller
 * 
 * @author ruoyi
 * @date 2025-09-25
 */
@RestController
@RequestMapping("/functiontest/RoadInterchangeTest")
public class RoadInterchangeTestController extends BaseController
{
    @Autowired
    private IRoadInterchangeTestService roadInterchangeTestService;

    /**
     * 查询枢纽互通里程实测数据测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:list')")
    @GetMapping("/list")
    public AjaxResult list(RoadInterchangeTest roadInterchangeTest)
    {
        List<RoadInterchangeTest> list = roadInterchangeTestService.selectRoadInterchangeTestList(roadInterchangeTest);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = roadInterchangeTest.getRoadName() != null && !roadInterchangeTest.getRoadName().isEmpty() ||
                                   roadInterchangeTest.getInterchangeName() != null && !roadInterchangeTest.getInterchangeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<RoadInterchangeTest> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出枢纽互通里程实测数据测试列表
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:export')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RoadInterchangeTest roadInterchangeTest)
    {
        List<RoadInterchangeTest> list = roadInterchangeTestService.selectRoadInterchangeTestListForExport(roadInterchangeTest);
        ExcelUtil<RoadInterchangeTest> util = new ExcelUtil<RoadInterchangeTest>(RoadInterchangeTest.class);
        util.exportExcel(response, list, "枢纽互通里程实测数据测试数据");
    }

    /**
     * 获取枢纽互通里程实测数据测试详细信息
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(roadInterchangeTestService.selectRoadInterchangeTestById(id));
    }

    /**
     * 新增枢纽互通里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:add')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RoadInterchangeTest roadInterchangeTest)
    {
        return toAjax(roadInterchangeTestService.insertRoadInterchangeTest(roadInterchangeTest));
    }

    /**
     * 修改枢纽互通里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:edit')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RoadInterchangeTest roadInterchangeTest)
    {
        return toAjax(roadInterchangeTestService.updateRoadInterchangeTest(roadInterchangeTest));
    }

    /**
     * 删除枢纽互通里程实测数据测试
     */
    @PreAuthorize("@ss.hasPermi('functiontest:RoadInterchangeTest:remove')")
    @Log(title = "枢纽互通里程实测数据测试", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 检查是否可以删除节点（父节点必须在子节点删除完后才能删除）
        for (Long id : ids) {
            if (roadInterchangeTestService.hasChildById(id)) {
                return error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        
        return toAjax(roadInterchangeTestService.deleteRoadInterchangeTestByIds(ids));
    }
    
    /**
     * 构建树形结构
     */
    private List<RoadInterchangeTest> buildTree(List<RoadInterchangeTest> list) {
        // 构建父子关系映射
        Map<Long, RoadInterchangeTest> nodeMap = new HashMap<>();
        List<RoadInterchangeTest> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (RoadInterchangeTest node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (RoadInterchangeTest node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                RoadInterchangeTest parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<RoadInterchangeTest>());
                    }
                    @SuppressWarnings("unchecked")
                    List<RoadInterchangeTest> children = (List<RoadInterchangeTest>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }
}
